<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户管理</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        .toolbar {
            margin-bottom: 20px;
        }

        .dialog-footer {
            text-align: right;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input placeholder="搜索用户名" v-model="searchKeyword" style="width: 200px;"
                      ></el-input>
        </div>
        <el-table :data="users" stripe>
            <el-table-column prop="fullname" label="姓名"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
            <el-table-column label="头像">
                <template slot-scope="scope">
                    <el-image :src="scope.row.avatar" style="width: 50px; height: 50px"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.isActive"
                            @change="handleStatusChange(scope.row)"
                            active-value="true"
                            inactive-value="false"
                    >
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="mini">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="danger" size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalUsers">
            </el-pagination>
        </div>
    </el-card>

    <el-dialog title="用户信息" :visible.sync="dialogVisible">
        <el-form :model="currentUser" :rules="rules" ref="userForm" label-width="100px">
            <el-form-item label="用户名" prop="username">
                <el-input disabled v-model="currentUser.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="fullname">
                <el-input v-model="currentUser.fullname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="currentUser.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="currentUser.phoneNumber" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                users: [],
                totalUsers: 0,
                pageSize: 5,
                currentPage: 1,
                dialogVisible: false,
                currentUser: {},
                isEditMode: false,
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    fullname: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {type: 'email', message: '请输入有效的邮箱', trigger: 'blur'}
                    ],
                    phoneNumber: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {pattern: /^1[34578]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur'}
                    ]
                }
            };
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1; // 重置当前页码为1
                    this.fetchUsers(); // 重新获取用户数据
                }
            },
            currentPage(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchUsers(); // 重新获取用户数据
                }
            },
            pageSize(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchUsers(); // 重新获取用户数据
                }
            }
        },
        methods: {
            fetchUsers() {
                axios.get('/user?operation=findUsersByPageAndName', {
                    params: {
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.users = data.data; // 更新数据字段为 data.data
                        this.totalUsers = data.total;
                    } else {
                        this.$message.error('获取用户列表失败');
                    }
                }).catch(error => {
                    console.error('获取用户列表失败:', error);
                    this.$message.error('获取用户列表失败');
                });
            },
            handleEdit(user) {
                this.isEditMode = true;
                this.currentUser = Object.assign({}, user);
                this.dialogVisible = true;
            },
            handleSave() {
                this.$refs.userForm.validate(valid => {
                    if (valid) {
                        const url = this.isEditMode ? '/user?operation=updateUser' : '/user?operation=register';
                        axios.post(url, this.currentUser)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success(this.isEditMode ? '用户信息更新成功' : '用户添加成功');
                                    this.fetchUsers();
                                } else {
                                    this.$message.error(this.isEditMode ? '用户信息更新失败' : '用户添加失败');
                                }
                            })
                            .catch(error => {
                                console.error(this.isEditMode ? '用户信息更新失败:' : '用户添加失败:', error);
                                this.$message.error(this.isEditMode ? '用户信息更新失败' : '用户添加失败');
                            });
                        this.dialogVisible = false;
                    }
                });
            },
            handleDelete(user) {
                if (user.username == 'admin') {
                    this.$message.error("管理员不可删除！！")
                    this.fetchUsers();
                    return false;
                }
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/user?operation=deleteUser&userId=' + user.id)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('用户删除成功');
                                this.fetchUsers();
                            } else {
                                this.$message.error('用户删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('用户删除失败:', error);
                            this.$message.error('用户删除失败');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },
            handleStatusChange(user) {
                if (user.username == 'admin') {
                    this.$message.error("管理员不可禁用！！")
                    this.fetchUsers();
                    return false;
                }
                axios.post('/user?operation=updateUser', {
                    id: user.id,
                    isActive: user.isActive
                }).then(response => {
                    if (response.data.code === 200) {
                        this.$message.success('用户状态更新成功');
                    } else {
                        this.$message.error('用户状态更新失败');
                    }
                }).catch(error => {
                    console.error('用户状态更新失败:', error);
                    this.$message.error('用户状态更新失败');
                });
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            }
        },
        mounted() {
            this.fetchUsers();
        }
    });
</script>

</body>
</html>